package com.wql.crypto.common;

/**
 * 16进制工具类
 * 
 * @author wuqinglong
 */
public class HexUtils {
	private HexUtils() {
	}

	private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	/**
	 * 二进制字节转换成十六进制字符串
	 * 
	 * @param data
	 * @return
	 */
	public static String byte2HexStr(final byte[] data) {
		final int l = data.length;
		final char[] out = new char[l << 1];
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = DIGITS_UPPER[(0xF0 & data[i]) >>> 4];
			out[j++] = DIGITS_UPPER[0x0F & data[i]];
		}
		return new String(out);
	}

	/**
	 * 十六进制字符串转换成二进制字节
	 * 
	 * @param data
	 * @return
	 */
	public static byte[] hexStr2byte(final String data) {
		try {
			final char[] dataArr = data.toCharArray();
			final int len = dataArr.length;
			if ((len & 0x01) == 0) {
				final byte[] out = new byte[len >> 1];
				for (int i = 0, j = 0; j < len; i++) {
					int f = Character.digit(dataArr[j++], 16) << 4;
					f = f | Character.digit(dataArr[j++], 16);
					out[i] = (byte) (f & 0xFF);
				}
				return out;
			}
		} catch (Exception e) {
		}
		return null;
	}

}
